<template>
  <a-drawer
    :width="350"
    :visible="visible"
    title="详情"
    @cancel="cancel"
    :hide-cancel="false"
    :header="false"
    :popup-container="props.container"
  >
    <div class="approval-drawer">
      <div class="users">
        <div
          class="user-item"
          v-for="userItem in currUserList"
          :key="userItem?.id"
        >
          <PersonnelIcon
            :name="
              userItem?.nickname
                ? userItem?.nickname
                : userItem?.username
                ? userItem?.username
                : userItem?.name
            "
            :head-portraits="userItem?.headPortrait"
          />
          <div class="user-name">
            {{
              userItem?.nickname
                ? userItem?.nickname
                : userItem?.username
                ? userItem?.username
                : userItem?.name
            }}
          </div>
        </div>
        <!-- <template> -->
        <div class="user-item" @click="addUser">
          <div>
            <a-button style="height: 48px; width: 48px">
              <template #icon>
                <icon-plus :size="24" />
              </template>
            </a-button>
          </div>
          <div class="user-name">新增</div>
        </div>
        <div
          class="user-item"
          v-if="[2, 3].includes(Number(groupBaseInfo?.identity))"
          @click="removeUser"
        >
          <div>
            <a-button style="height: 48px; width: 48px">
              <template #icon>
                <icon-minus :size="24" />
              </template>
            </a-button>
          </div>
          <div class="user-name">移除</div>
        </div>
        <!-- </template> -->
      </div>
      <div class="extend">
        <a-button
          type="text"
          @click="showMore"
          v-if="!isShowMore && groupUserList?.length > initUserCount"
        >
          展开更多
          <icon-down />
        </a-button>
        <a-button type="text" @click="close" v-if="isShowMore">
          收起
          <icon-up />
        </a-button>
      </div>
      <div class="group-base-info">
        <a-form :model="groupBaseInfo" :layout="'vertical'">
          <a-form-item field="name" label="群聊名称">
            <a-input
              :disabled="groupBaseInfo?.identity === 1"
              v-model="groupBaseInfo.name"
              placeholder="输入群聊名称"
              @change="changeBaseInfo"
            />
          </a-form-item>
          <a-form-item field="notice" label="群公告">
            <a-input
              :disabled="groupBaseInfo.identity === 1"
              ref="noticeInputRef"
              v-model="groupBaseInfo.notice"
              placeholder="输入群公告"
              @change="changeNotice"
              @focus="noticeFocus"
            />
          </a-form-item>
          <a-form-item field="note" label="备注">
            <a-input
              v-model="groupBaseInfo.note"
              placeholder="备注"
              @change="changeMyInfo"
            />
          </a-form-item>
          <a-form-item field="nickname" label="我在本群昵称">
            <a-input
              v-model="groupBaseInfo.nickname"
              placeholder="我在本群昵称"
              @change="changeMyInfo"
              ref="inputRef"
            />
          </a-form-item>
        </a-form>
      </div>
    </div>
    <template #footer>
      <div class="drawer-footer">
        <a-popconfirm content="确定退出群聊?" type="warning" @ok="quitGroup">
          <a-button type="text" status="danger" :size="'large'">
            退出群聊</a-button
          >
        </a-popconfirm>
      </div>
    </template>
  </a-drawer>
  <ContactGroupCreate
    v-model:visible="groupCreateVisible"
    :alreadyList="alreadyList"
    @groupCreate="groupCreate"
  />
  <ContactGroupRemove
    v-model:visible="groupRemoveVisible"
    :teamUsers="groupUserList"
    @groupRemove="groupRemove"
  />
</template>

<script setup lang="ts">
import PersonnelIcon from './PersonnelIcon.vue';
import ContactGroupCreate from '../../AddressBook/components/ContactGroupCreate.vue';
import ContactGroupRemove from '../../AddressBook/components/ContactGroupRemove.vue';
import {
  addGroupUser,
  getGroupBaseInfo,
  editGroupMyInfo,
  editGroupInfo,
  quitGroupByGroupId,
  delGroupUser,
  getContactGroupUserList
} from '@/apis/client/addressBook/index';
import { useClientContactsStore } from '@/store';
import { Notification } from '@arco-design/web-vue';
import { cloneDeep } from 'lodash';
import mitter from '../../../../../utils/mitt';

const props = withDefaults(
  defineProps<{
    visible: boolean;
    container?: string;
    groupInfo?: any;
  }>(),
  {
    visible: false
  }
);
const emit = defineEmits(['update:visible', 'editGroupName']);
const cancel = () => {
  emit('update:visible', false);
};

const contactStore = useClientContactsStore();

interface GroupInfo {
  /**
   * 身份，1 普通成员 2 管理 3 群主
   */
  identity?: number;
  /**
   * 群名称
   */
  name?: string;
  /**
   * 我在本群的昵称
   */
  nickname?: string;
  /**
   * 备注
   */
  note?: string;
  /**
   * 群公告
   */
  notice?: string;
}
const groupBaseInfo = ref<GroupInfo>({}); // 群基本信息
// 获取群基本信息
const getGroupInfo = async () => {
  const id = Number(props.groupInfo.groupInfo.id);
  if (!id) return;
  const res = await getGroupBaseInfo({ id });
  groupBaseInfo.value = res || {};
};

let groupUserList = ref([]);
// 获取群成员信息
const getGroupUser = async () => {
  const id = props.groupInfo?.groupId;
  if (!id) return;
  const res = await getContactGroupUserList({
    id,
    pageNumber: 0,
    pageSize: -1
  });
  groupUserList.value = res.content || [];
  initUserList(groupUserList.value);
  currGroupId = id;
  alreadyList.value = groupUserList.value.map((item: any) => item.userId);
};
watch(
  () => props.visible,
  (val) => {
    if (!val || !props.groupInfo?.groupInfo?.id) return;
    isShowMore.value = false;
    getGroupInfo();
    getGroupUser();
  }
);

let currUserList = ref([]); // 当前要显示的列表
let initUserCount = 14; // 储存最低显示个数，用于判断一但超过则显示展开更多按钮
let alreadyList = ref([]); // 已经在群里面的id
let currGroupId = 0; // 当前群聊的id
// 初始化要显示的人员列表数据
const initUserList = (data: any) => {
  currUserList.value = [];
  for (let i = 0; i < initUserCount; i++) {
    if (data[i]) currUserList.value.push(data[i]);
    else break;
  }
};

// watch(
//   () => props.users,
//   (newVal: any) => {
//     if (newVal.length > 0) {
//       initUserList(newVal);
//       currGroupId = newVal[0].groupId;
//       alreadyList.value = newVal.map((item: any) => item.userId);
//     }
//   }
// );

let isShowMore = ref(false);
// 展开更多
const showMore = () => {
  currUserList.value = groupUserList.value;
  isShowMore.value = true;
};

// 收起
const close = () => {
  currUserList.value = [];
  initUserList(groupUserList.value);
  isShowMore.value = false;
};

let groupCreateVisible = ref(false);
//新增群聊
const groupCreate = async (data: any[]) => {
  // if (!data.length) return;
  let ids = data.map((item) => item.id);
  await addGroupUser({
    groupId: currGroupId,
    userId: ids
  });
  getGroupUser();
};

// 新增成员弹出框
const addUser = () => {
  groupCreateVisible.value = true;
};

let groupRemoveVisible = ref(false);

// 移除成员弹出框
const removeUser = () => {
  groupRemoveVisible.value = true;
};

// 移除成员弹框自定义事件
const groupRemove = async (ids: number[]) => {
  await delGroupUser({
    groupId: currGroupId,
    userId: ids
  });
  getGroupUser();
};

const inputRef = ref();
const changeMyInfo = (value: any, ev: any) => {
  ev.target.blur();
  updateGroupMyInfo();
};
// 修改群基本信息
const changeBaseInfo = async (v: any, ev: any) => {
  const { name } = groupBaseInfo.value;
  const params = { name, groupId: props.groupInfo?.groupInfo?.id };
  await editGroupInfo(params);
  Notification.success('修改成功');
  emit('editGroupName', name);
};
//修改群公告
const changeNotice = async (v: any, ev: any) => {
  const { notice } = groupBaseInfo.value;
  const params = { notice, groupId: props.groupInfo?.groupInfo?.id };
  await editGroupInfo(params);
};
//修改群我的信息
const updateGroupMyInfo = async () => {
  let { nickname, note } = groupBaseInfo.value;
  note = note ? note : void 0;
  const params = { nickname, note, groupId: props.groupInfo?.groupInfo?.id };
  await editGroupMyInfo(params);
  getGroupUser();
};
/**
 * 退出群聊
 */
const quitGroup = async () => {
  const id = props.groupInfo.groupInfo.id;
  await quitGroupByGroupId({ id });
  contactStore.isQuitGroup = true;
  cancel();
};
const noticeInputRef = ref();
/**
 * 判断是否有权限发布公告
 */
const noticeFocus = () => {
  if (groupBaseInfo.value.identity === 1) {
    noticeInputRef.value.blur();
    Notification.error('你没有权限发布和修改公告！');
  }
};
</script>

<style lang="less" scoped>
.approval-drawer {
  .users {
    display: flex;
    flex-wrap: wrap;
    // border-bottom: 1px solid #eee;
    // padding-bottom: 16px;

    .user-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      margin: 0 10px 10px 10px;
    }
  }
  .extend {
    text-align: center;
    :deep(.arco-btn-text) {
      color: #000;
    }
  }
  .group-base-info {
    margin-top: 10px;
    border-top: 1px solid #eee;
  }
}
.drawer-footer {
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
}
</style>
